package com.dc.controller;

import com.dc.base.aop.AopOperation;
import com.dc.base.baseController.BaseController;
import com.dc.base.em.ErrorMessageEnum;
import com.dc.base.em.RoleMenuEnum;
import com.dc.base.utils.MD5DES;
import com.dc.base.utils.RSAUtils;
import com.dc.base.vo.BaseModel;
import com.dc.base.vo.BusinessException;
import com.dc.model.LoginLog;
import com.dc.model.User;
import com.dc.service.LoginLogService;
import com.dc.service.RoleService;
import com.dc.service.UserService;
import com.wordnik.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

@Api(value="用户模块")
@RequestMapping("/user")
@Controller
public class UserController extends BaseController {

    @Autowired UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    LoginLogService loginLogService;

    @AopOperation(desc = "分页查询用户信息",type = "查询",menu = RoleMenuEnum.No_101)
    @ApiOperation(value="分页查询用户信息",httpMethod = "GET",notes = "查询")
    @RequestMapping(value = "/selectPageUser", method = RequestMethod.GET)
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(value = "当前页码", name = "curr_page", defaultValue = "1", dataType = "int",paramType = "query"),
            @ApiImplicitParam(value = "一页的最大条数", name = "page_size", defaultValue = "10", dataType = "int",paramType = "query")
    })
    public BaseModel selectPageUser(
            @RequestParam(value="curr_page",defaultValue = "1") int curr_page,
            @RequestParam(value="page_size",defaultValue = "10") int page_size,
            BaseModel baseModel,
            @RequestParam(value="account",required = false) String account,
            @RequestParam(value="name",required = false)String name){
        return  userService.selectPageUser(curr_page,page_size,baseModel,account,name);

    }

    // 校验通过提示登录成功！，否则提示相应错误消息
    @ApiOperation(value="登录",httpMethod = "POST",notes = "查询")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public BaseModel login(@RequestParam(value  ="account", required = true) String account,
                                 @RequestParam(value="password",required = true) String password,
                                    BaseModel baseModel,
                                    HttpServletRequest request

    )throws Exception{
        //抛出系统异常 Exception
        if(account==null||password==null){
            throw new BusinessException(ErrorMessageEnum.FORMAT_ERROR);
        }
        HttpSession session =request.getSession();
        //pwd是一个密文，需要先解密出明文再比对
            String whiltePwd=RSAUtils.sessionDecryptHexStr(session,password);
       // 将明文转化成md5后的密文
        String md5Pwd=MD5DES.encrypt(whiltePwd);
        // 调用业务层
        baseModel=userService.login(account,md5Pwd,baseModel);
        // 将登录用户的数据存入到session
        if(baseModel.getResultCode()==0){
            Date date= new Date();
            session.setAttribute("data",date);
            session.setAttribute("currentUser",baseModel.getData());
            User user=(User)baseModel.getData();
            //权限信息
            session.setAttribute("permission",roleService.getRolePermissionByUserId(user.getUser_id()));
        }
        return baseModel;
    }
// 登出
    @ApiOperation(value="注销",httpMethod = "POST",notes = "查询")
    @RequestMapping(value = "/loginout", method = RequestMethod.POST)
    @ResponseBody
    public BaseModel loginout(LoginLog loginLog,BaseModel baseModel, HttpServletRequest request)throws Exception{
        HttpSession session=request.getSession();
        User currentUser = (User)session.getAttribute("currentUser");
        loginLog.setUser_id(currentUser.getUser_id());
        loginLog.setUser_name(currentUser.getName());
        loginLog.setUser_account(currentUser.getAccount());
        loginLog.setUser_password("");
        loginLog.setLogin_time(currentUser.getCreate_time());
        loginLog.setLoginout_time(new Date());
        loginLog.setVersion(currentUser.getVersion());
        baseModel=loginLogService.addLoginLog(loginLog,baseModel);
        // 移除登录信息
        request.getSession().removeAttribute("currentUser");
        return baseModel;
    }

    // 完成新增接口，要求所有的错误都由统一异常处理机制处理
    @AopOperation(desc = "新增用户操作",type = "新增",menu = RoleMenuEnum.No_101)
    @ApiOperation(value="用户新增",httpMethod = "POST",notes="新增")
    @RequestMapping(value="/addUser", method = RequestMethod.POST)
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(value="账号",name="account",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value="姓名",name="name",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value="等级",name="level",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(value="密码",name="password",required = true,dataType = "String",paramType = "query")
    })
    public BaseModel addUser(User user,@RequestParam(value  ="account", required = true) String account,
                             @RequestParam(value="password",required = true) String password,
                             @RequestParam(value  ="level", required = true) String level,
                             @RequestParam(value="name",required = true) String name,HttpServletRequest request,BaseModel baseModel)throws Exception{
       // 前端数据校验。
        user.setVersion(0);
        user.setIs_delete(0);
        user.setState(0);
        user.setPassword(MD5DES.encrypt(password));
        user.setCreate_time(new Date());
        HttpSession session=request.getSession();
        User currUser=(User)session.getAttribute("currentUser");
        if(currUser==null) {
            throw new BusinessException(ErrorMessageEnum.LOGIN_TIMEOUT);
        }
       return userService.addUser(user,baseModel);
    }

    @ApiOperation(value="用户修改",httpMethod = "POST",notes="修改")
    @RequestMapping(value="/updateUser", method = RequestMethod.POST)
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(value="账号",name="account",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value="姓名",name="name",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value="等级",name="level",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(value="用户编号",name="user_id",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(value="版本号",name="version",required = true,dataType = "int",paramType = "query")
    })
    public BaseModel updateUser(User user,String birthdayStr,BaseModel baseModel,HttpServletRequest request)throws Exception {
        // 校验格式
        // 获取登录信息
        HttpSession session=request.getSession();
        User currentUser=(User)session.getAttribute("currentUser");
        // 时间字符串，时间
        if(currentUser==null){
            throw new BusinessException(ErrorMessageEnum.LOGIN_TIMEOUT);
        }

        user.setUpdate_time(new Date());

        return userService.updateUser(user,baseModel);
    }

    @AopOperation(desc = "删除用户信息",type = "删除",menu = RoleMenuEnum.No_101)
    @ApiOperation(value="用户删除",httpMethod = "POST",notes="删除")
    @RequestMapping(value="/deleteUser/{ids}", method = RequestMethod.POST)
    @ResponseBody
    public BaseModel deleteUser(@PathVariable(value="ids") String ids,
                                BaseModel baseModel,
                                HttpServletRequest request)throws Exception{
            HttpSession session=request.getSession();
            User currentUser=(User)session.getAttribute("currentUser");
            if(currentUser==null){
                throw new BusinessException(ErrorMessageEnum.LOGIN_TIMEOUT);
            }

            return userService.deleteUser(ids,baseModel);
    }

//    @ApiOperation(value="用户信息导入",httpMethod = "GET",notes="导入")
//    @RequestMapping(value="/impUserDTO", method = RequestMethod.GET)
//    @ResponseBody
//    public BaseModel impUserDTO(BaseModel baseModel) throws  Exception{
//        //调用导入servce
//        return null;
//    }


}
